package com.neusoft.nepa.controller;

import com.neusoft.nepa.UserLogin;
import com.neusoft.nepa.entity.*;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ColorMapController {
    @FXML private WebView mapView;
    @FXML private Label infoLabel;
    @FXML private Label Feedback;
    private UserLogin mainApp;
    private Map<String, Integer> provinceAqiData = new HashMap<>();
    private Map<String, String[]> provinceData = new HashMap<>();
    private boolean mapLoaded = false;

    public void initialize() {
        // 初始化省份AQI数据（保持原有逻辑）
        initProvinceAqiData();
        // 移除原有的地图加载逻辑，避免mainApp未注入时调用
    }

    private void initProvinceAqiData() {
        // 示例数据 - 实际应用中可以从数据库或API获取
        provinceAqiData.put("北京", 100);
        provinceAqiData.put("上海", 85);
        provinceAqiData.put("广东", 90);
        provinceAqiData.put("江苏", 105);
        provinceAqiData.put("浙江", 95);
        provinceAqiData.put("山东", 110);
        provinceAqiData.put("河南", 130);
        provinceAqiData.put("四川", 75);
        provinceAqiData.put("湖北", 100);
        provinceAqiData.put("福建", 65);
        provinceAqiData.put("湖南", 95);
        provinceAqiData.put("安徽", 100);
        provinceAqiData.put("河北", 140);
        provinceAqiData.put("陕西", 115);
        provinceAqiData.put("黑龙江", 80);
        provinceAqiData.put("辽宁", 105);
        provinceAqiData.put("江西", 85);
        provinceAqiData.put("广西", 70);
        provinceAqiData.put("云南", 60);
        provinceAqiData.put("山西", 125);
        provinceAqiData.put("贵州", 75);
        provinceAqiData.put("吉林", 90);
        provinceAqiData.put("甘肃", 110);
        provinceAqiData.put("内蒙古", 100);
        provinceAqiData.put("新疆", 95);
        provinceAqiData.put("海南", 50);
        provinceAqiData.put("宁夏", 115);
        provinceAqiData.put("青海", 80);
        provinceAqiData.put("西藏", 45);
        provinceAqiData.put("重庆", 95);
        provinceAqiData.put("天津", 120);
        provinceAqiData.put("台湾", 75);
    }

    private void loadMap() {
        // 关键修改：检查mainApp是否已注入，防止空指针
        if (mainApp == null || mapLoaded) {
            return;
        }

        // 加载地图（修正资源路径，移除/src前缀）
        WebEngine webEngine = mapView.getEngine();
        webEngine.load(mainApp.getClass().getResource("/com/neusoft/nepa/view/ChinaMap.svg").toExternalForm());

        // 等待地图加载完成后执行JavaScript
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == javafx.concurrent.Worker.State.SUCCEEDED) {
                mapLoaded = true; // 标记地图已加载
                // 执行JavaScript来处理地图
                applyProvinceColors(webEngine);
                setupProvinceClickHandlers(webEngine);
            }
        });
    }

    private void applyProvinceColors(WebEngine webEngine) {
        // 找到AQI的最大值和最小值，用于颜色映射
        int minAqi = Integer.MAX_VALUE;
        int maxAqi = Integer.MIN_VALUE;

        for (int aqi : provinceAqiData.values()) {
            minAqi = Math.min(minAqi, aqi);
            maxAqi = Math.max(maxAqi, aqi);
        }

        // 为每个省份设置颜色
        for (Map.Entry<String, Integer> entry : provinceAqiData.entrySet()) {
            String provinceName = entry.getKey();
            int aqi = entry.getValue();

            // 计算颜色 - 从绿色(0)到红色(255)的渐变
            double ratio = (double) (aqi - minAqi) / (maxAqi - minAqi);
            int red = (int) (255 * ratio);
            int green = (int) (255 * (1 - ratio));
            String color = String.format("#%02x%02x00", red, green);

            // 执行JavaScript设置省份颜色
            String script = String.format(
                    "document.querySelector('#%s').setAttribute('fill', '%s');",
                    provinceName.toLowerCase(), color
            );
            webEngine.executeScript(script);
        }
    }

    private void setupProvinceClickHandlers(WebEngine webEngine) {
        // 创建Java对象供JavaScript调用
        JSObject window = (JSObject) webEngine.executeScript("window");
        window.setMember("javaController", this);

        // 为每个省份添加点击事件
        String script = "var provinces = document.querySelectorAll('#china-map path');" +
                "provinces.forEach(function(province) {" +
                "    province.addEventListener('click', function() {" +
                "        var provinceName = this.getAttribute('data-name');" +
                "        javaController.onProvinceSelected(provinceName);" +
                "    });" +
                "    province.addEventListener('mouseover', function() {" +
                "        this.setAttribute('stroke', '#000');" +
                "        this.setAttribute('stroke-width', '2');" +
                "    });" +
                "    province.addEventListener('mouseout', function() {" +
                "        this.setAttribute('stroke', 'none');" +
                "    });" +
                "});";

        webEngine.executeScript(script);
    }

    // 供JavaScript调用的方法
    public void onProvinceSelected(String provinceName) {
        int aqi = provinceAqiData.getOrDefault(provinceName, 0);
        String aqi_level = "";
        if (aqi>=0&&aqi<=50) aqi_level = "一级污染";
        else if (aqi>=51&&aqi<=100) aqi_level = "二级污染";
        else if (aqi>=101&&aqi<=150) aqi_level = "三级污染";
        else if (aqi>=151&&aqi<=200) aqi_level = "四级污染";
        else if (aqi>=201&&aqi<=300) aqi_level = "五级污染";
        else if (aqi>=301) aqi_level = "六级污染";
        infoLabel.setText(String.format("%s - AQI: %d %s", provinceName, aqi, aqi_level));
        Feedback.setText(" ");
        Feedback.setText(provinceData.get(provinceName)[2]);
    }

    public void setMainApp(UserLogin userLogin) throws IOException {
        this.mainApp = userLogin;
        // 在设置mainApp后加载地图（关键修改点）
        loadMap();
        refreshMap();
    }

    public void refreshMap() throws IOException {
        provinceData = this.mainApp.InfoArrange();
        for (String provinceName : provinceData.keySet()) {
            int temp =Integer.parseInt(provinceData.get(provinceName)[0]);
            if (temp!=0) {
                provinceAqiData.put(provinceName, Integer.parseInt(provinceData.get(provinceName)[1]) / Integer.parseInt(provinceData.get(provinceName)[0]));
            }
        }
    }
    @FXML
    private void handleAdmin() throws IOException {
        mainApp.showAdminView();
    }
}